from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.views.decorators.cache import cache_page
from stocksys.sys_tasks.logic_function import get_realtime_stock_content
from stocksys.views.data_logic import *
from stocksys.views.user_views import check_login
from stocksys.views.views import init_message


@check_login
@cache_page(60)
def fund_list(request):
    context = init_message(request)
    user = auth_models.User.objects.get(id=request.session.get('id'))
    sysconf = stocksys_models.SysConf.objects.get(user=user)
    context["title"] = "量化分析系统-基金列表"
    _funds = stocksys_models.Fund.objects.all()
    exchanges = []
    for exchange in _funds:
        fund_code = "%s%s" % (exchange.exchange_address.stock_sina_name, exchange.code)
        info = get_realtime_stock_content(fund_code)
        exchange_chg = 0
        if info['current'] != 0:
            exchange_chg = (info['current'] - info['close']) / info['close']
        if exchange_chg < 0:
            color = 'success'
        elif exchange_chg == 0:
            color = 'warning'
        else:
            color = 'danger'
        exchanges.append({
            'name': exchange.name,
            'abbreviated_name': exchange.abbreviated_name,
            'exchange_address': exchange.exchange_address,
            'code': exchange.code,
            'type': exchange.type,

            'open': info['open'],
            'close': info['close'],
            'current': info['current'],
            'chg': exchange_chg * 100,
            'chg_price': exchange_chg,
            'color': color,
            'volume': info['v_num'] / 10000,
            'money': info['money'] / 10000,
            "systime": datetime.datetime.now().strftime('%Y-%m-%d'),
        })
    context["exchanges"] = exchanges
    context["now_year"] = int(time.strftime('%Y', time.localtime(time.time())))
    context["quant_start_date"] = sysconf.predict_start_time.strftime("%Y-%m-%d")
    context["quant_end_date"] = sysconf.predict_end_time.strftime("%Y-%m-%d")
    context["predict_type"] = 'fund'
    context["spider_mode"] = False
    if settings.USE_JQDATA_SDK:
        context["spider_mode"] = True
    return render(request, "stocksys/table_list/exchange_table.html", context)


@check_login
def fund_info(request, code, addr, year=None):
    fund = stocksys_models.Fund.objects.get(code=code, exchange_address=addr)
    if request.method == "GET":
        context = init_message(request)
        context["title"] = "量化分析系统-股票信息"
        context["fund_address"] = fund.exchange_address.stock_address_name
        context["fund"] = fund
        return render(request, "stocksys/info/fund_info.html", context)
    elif request.method == "POST":
        now_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        now_year = str(time.strftime('%Y', time.localtime(time.time())))

        info = {"statue": 500, "data": []}
        if settings.USE_JQDATA_SDK:
            jqdata_code="%s.%s" % (code, fund.exchange_address.stock_jqdata_name)
            api_keys = stocksys_models.APIKeys.objects.all().first()
            jqdatasdk.auth(api_keys.username, api_keys.password)
            resources = jqdatasdk.attribute_history_engine(end_dt=now_date, count=365, security=jqdata_code, unit='1d',
                                                           skip_paused=True,
                                                           df=True, fq=None)
            jqdatasdk.logout()
            info = resources2infojson(resources, fund.name)

        else:
            # TODO:不使用JQDATA数据平台
            pass
        # TODO:单支基金数据
        return JsonResponse(info)


@check_login
def fund_time_info(request, code):
    # TODO:单支基金数据
    return JsonResponse({"statue": 200, "page": "fund_time_info"})
